import create from 'zustand';
import { persist } from 'zustand/middleware';
import menuStore from './menu';

export interface Role {
  id: string;
  roleString: string;
}
export interface OperationsList {
  createDateTime: number;
  creator: string;
  id: string;
  isSoftDelete: boolean;
  name: string;
  pageId: string;
  router: string;
}
export interface UserPermission {
  actionUrl: string;
  button: boolean;
  createDateTime: number;
  creator: string;
  id: string;
  idPath: string;
  isSoftDelete: boolean;
  label: string;
  permissionTreeVOList: UserPermission[];
  remarks: string;
  router: string;
  sort: number;
  type: string;
  operationsList?: OperationsList[];
  permissionPid?: string;
}

export interface UserInfo {
  realName: string;

  area: {
    areaId: string;
    areaName: string;
  }[];
  token: string;
  userType: string;
  userId: string;
  username: string;
  certificatesId: string;
  jobName: string;
  mobile: string;
  mailbox: string;
  roles: Role[];
  userPermissions: UserPermission[];
}

export type UserStore = {
  userinfo: UserInfo;
  token: string;
  setUser: (user: UserInfo) => void;
  setToken: (token: string) => void;
  logout: (search: string) => void;
};

/**
 * 用户信息 store
 */
const useUserStore = create<UserStore>(
  persist(
    (set, get) => ({
      userinfo: {} as UserInfo,
      token: '',
      setUser(payload: UserInfo) {
        set({ userinfo: payload });
      },
      setToken(token: string) {
        set({ token });
      },
      logout(search: string) {
        const t = get();
        t.setUser({} as UserInfo);
        t.setToken('');
        menuStore.getState().setPermissions([]);
        window.location.href = `/login?redirect=${search}`;
        // history.replace(`/login?redirect=${search}`);
      }
    }),
    {
      name: 'user'
    }
  )
);

export default useUserStore;
